""" 
SG90舵机

接线:
    IO控制线 --> GPIO17
"""

from machine import Pin, PWM
import time


class Servo:
    def __init__(self, pin_num, freq):
        self.pin_num = pin_num
        self.freq = freq
        self.pwm = PWM(Pin(pin_num), freq=freq, duty=0)
        self.pwm_time = 1 / freq * 1000     # 单位ms

    def write_angle(self, angle):
        pwm_h_time = 0.5 + 2.0 / 180 * angle
        """ 计算公式:
        pwm_h_time: 方波高电平时间/ms
        pwm_time: 方波周期/ms
        duty: 占空比
        1024: 16位PWM分辨率

        pwm_h_time/pwm_time = duty/1024
        duty = pwm_h_time * 1024 / pwm_time
        """
        duty = int(pwm_h_time * 1023 / self.pwm_time)
        print("pwm_h_time:{}ms, duty: {}".format(pwm_h_time, duty))
        self.pwm.duty(duty)


servo = Servo(17, 50)

if __name__ == "__main__":
    while True:
        servo.write_angle(0)
        time.sleep(2)
        servo.write_angle(45)
        time.sleep(2)
        servo.write_angle(90)
        time.sleep(2)
        servo.write_angle(180)
        time.sleep(2)
